<template>
  <div class="products-page">
    <NavHeader
      title="全部商品"
      @back="onClickLeft"
    />
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="searchValue"
        placeholder="搜索商品"
        shape="round"
        background="transparent"
        @search="onSearch"
      />
      <div class="confirm-btn" @click="onConfirm">
        <van-icon name="success" />
        <span>确认</span>
      </div>
    </div>
    
    <!-- 分类标签 -->
    <div class="category-tabs">
      <van-tabs v-model:active="activeCategory" sticky swipeable animated @change="onCategoryChange">
        <van-tab v-for="category in categories" :key="category.id" :title="category.name">
          <!-- 下拉刷新和上拉加载组件 -->
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
            <van-list
              v-model:loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <!-- 商品列表 -->
              <div class="product-list">
                <div 
                  v-for="product in productList" 
                  :key="product.id" 
                  class="product-card"
                  @click="goToDetail(product.id)"
                >
                  <div class="product-image">
                    <img :src="imageUrl(product.images)" :alt="product.productName">
                    <div v-if="product.hot" class="discount-tag">热销产品</div>
                  </div>
                  <div class="product-info">
                    <div class="product-name">{{ product.productName }}</div>
                    <div class="product-desc">{{ product.detail }}</div>
                    <div class="product-price-row">
                      <div class="product-price">
                        <span class="price-symbol">$</span>
                        <span class="price-value">{{ productPrice(product.specs) }}{{ product.payIcon }}</span>
                        <!-- <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span> -->
                      </div>
                      <div class="product-sales">已售{{ product.sales }}件</div>
                    </div>
                  </div>
                </div>
              </div>
            </van-list>
          </van-pull-refresh>
        </van-tab>
      </van-tabs>
    </div>
    
    <!-- 空的弹出层，已移除所有筛选内容 -->
    
    <!-- 返回顶部按钮 -->
    <van-back-top right="16px" bottom="80px" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import NavHeader from '@/components/NavHeader.vue'
import { getGoodsList } from '@/api/goods'

const router = useRouter()
const searchValue = ref('')
const activeCategory = ref(0)
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = ref(10)
const productList = ref([])

// 分类数据
const categories = [
  { id: '', name: '全部' },
  { id: '推荐', name: '热门推荐' },
  { id: '数码', name: '数码产品' },
  { id: '健康', name: '健康产品' }
]


onMounted(() => {
  // 初始加载数据
  loadProducts()
})

// 下拉刷新
const onRefresh = () => {
  // 重置页码
  page.value = 1
  finished.value = false
  productList.value = []
  
  // 重新加载数据
  loadProducts().then(() => {
    refreshing.value = false
  })
}

// 上拉加载
const onLoad = () => {
  // 加载下一页数据
  page.value += 1
  loadProducts()
}

// 加载商品数据
const loadProducts = async () => {
  try {
    loading.value = true
    
    // 调用商品列表接口
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      cateName: categories[activeCategory.value].id,
      productName: searchValue.value
    }
    
    const response = await getGoodsList(params)
    
    // 检查接口返回状态和数据
    if (response.code === 0) {
      // 如果返回的列表不为空，则添加到现有列表中
      if (response.data && response.data.list && response.data.list.length > 0) {
        if (page.value === 1) {
          // 第一页数据直接替换
          productList.value = response.data.list
        } else {
          // 加载更多数据时追加
          productList.value = [...productList.value, ...response.data.list]
        }
      } else {
        // 如果返回的列表为空，标记为已加载完成
        finished.value = true
      }
    } else {
      // 接口返回错误
      console.error('获取商品列表失败', response.msg || '未知错误')
      finished.value = true
    }
  } catch (error) {
    console.error('获取商品列表失败', error)
    finished.value = true
  } finally {
    loading.value = false
  }
}

const imageUrl = (iamges) =>{
  if(iamges){
    return iamges.split(',')[0]
  }
  return ''
}

const productPrice = (goodSpec) =>{
  if(goodSpec && goodSpec.length > 0 ){
    return goodSpec[0].usdtPrice
  }
  return '12000'
}

// 重置并重新加载数据
const resetAndReload = () => {
  page.value = 1
  finished.value = false
  productList.value = []
  loadProducts()
}

// 搜索商品
const onSearch = () => {
  resetAndReload()
}

// 确认按钮点击事件
const onConfirm = () => {
  resetAndReload()
}

// 分类切换事件
const onCategoryChange = () => {
  resetAndReload()
}

// 跳转到商品详情
const goToDetail = (id) => {
  router.push(`/product/${id}`)
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}
</script>

<style scoped>
.products-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 20px;
  padding-top: 44px;
  max-width: 800px;
  margin: 0 auto;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: white;
  position: sticky;
  top: 44px;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-bar :deep(.van-search) {
  flex: 1;
  padding: 0;
}

.search-bar :deep(.van-search__content) {
  background-color: #f5f7fa;
}

.confirm-btn {
  display: flex;
  align-items: center;
  padding: 0 12px;
  color: var(--primary-color);
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  background-color: rgba(9, 96, 197, 0.1);
  border-radius: 16px;
  height: 32px;
}

.confirm-btn .van-icon {
  margin-right: 4px;
  font-size: 16px;
}

/* 分类标签 */
.category-tabs {
  background-color: white;
}

.category-tabs :deep(.van-tabs__wrap) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.category-tabs :deep(.van-tab) {
  font-size: 14px;
  padding: 0 16px;
}

.category-tabs :deep(.van-tabs__line) {
  background-color: var(--primary-color);
}

/* 商品列表 */
.product-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 12px;
}

.product-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product-card:active {
  transform: scale(0.98);
}

.product-image {
  position: relative;
  width: 100%;
  padding-top: 100%; /* 1:1 宽高比 */
  overflow: hidden;
}

.product-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.discount-tag {
  position: absolute;
  top: 8px;
  right: 0;
  background-color: #ff4d4f;
  color: white;
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 12px 0 0 12px;
}

.product-info {
  padding: 10px;
}

.product-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
}

.product-desc {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.product-price {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 12px;
  color: #ff4d4f;
  margin-right: 2px;
}

.price-value {
  font-size: 16px;
  font-weight: 700;
  color: #ff4d4f;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
  margin-left: 4px;
}

.product-sales {
  font-size: 12px;
  color: #999;
}

/* 已移除筛选弹出层相关样式 */
</style>